package cn.yuxiaoyuan.system.controller;

import cn.yuxiaoyuan.annotation.PreAuthorize;
import cn.yuxiaoyuan.system.domain.Permission;
import cn.yuxiaoyuan.system.query.PermissionQuery;
import cn.yuxiaoyuan.system.service.PermissionService;
import cn.yuxiaoyuan.utils.R;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/permission")
public class PermissionController {
    @Autowired
    private PermissionService permissionService;

    @PreAuthorize(sn = "permission:findById",name = "根据id查询权限",descs = "根据id查询权限")
    @GetMapping("/{id}")
    public R findById(@PathVariable("id") Long id) {
        return R.ok(permissionService.findById(id));
    }

    @PreAuthorize(sn = "permission:findAll",name = "查询所有权限",descs = "查询所有权限")
    @GetMapping
    public R findAll() {
        return R.ok(permissionService.findAll());
    }

    @PreAuthorize(sn = "permission:deleteById",name = "根据id删除权限",descs = "根据id删除权限")
    @DeleteMapping("/{id}")
    public R deleteById(@PathVariable("id") Long id) {
        permissionService.deleteById(id);
        return R.ok();
    }

    @PreAuthorize(sn = "permission:deleteAll",name = "根据ids删除权限",descs = "根据ids删除权限")
    @PostMapping("/deleteAll")
    public R batchDelete(@RequestBody List<Long> ids) {
        permissionService.batchDelete(ids);
        return R.ok();
    }

    @PreAuthorize(sn = "permission:add",name = "添加和修改权限",descs = "添加和修改权限")
    @ApiOperation("添加和修改")
    @PostMapping
    public R add(@RequestBody Permission permission) {
        if (permission.getId() == null) {
            permissionService.add(permission);
        } else {
            permissionService.update(permission);
        }
        return R.ok();
    }

    @PreAuthorize(sn = "permission:getPage",name = "权限的分页查询",descs = "权限的分页查询")
    @PostMapping("/page")
    public R getPage(@RequestBody PermissionQuery query) {
        PageHelper.startPage(query.getPage(), query.getSize());
        List<Permission> permissions = permissionService.queryPage(query);
        PageInfo<Permission> pageInfo = new PageInfo<>(permissions);
        return R.ok(pageInfo);
    }
}
